<?php
class local extends Model {

    protected $request;
    protected $session;

    public function __construct($registry) {
        parent::__construct($registry);
        $this->request = $registry->get('request');
        $this->session = $registry->get('session');
    }

    public function get_languages(){
        $sql = "SELECT * FROM " . $this->setting->get('db_prefix') . "language WHERE status = '1'";

        $query = $this->pdo->prepare($sql);
        $query->execute();
        $results = $query->fetchAll(PDO::FETCH_ASSOC);

        foreach ($results as $result) {
            $languages[$result['code']] = $result;
        }
        return $languages;
    }

    public function get_language($code = 'en'){

        $request = $this->request;
        $session = $this->session;

        $languages = $this->get_languages();    
        $detect = '';

        if (isset($request->server['HTTP_ACCEPT_LANGUAGE']) 
            && $request->server['HTTP_ACCEPT_LANGUAGE']) { 
                $browser_languages = explode(',', $request->server['HTTP_ACCEPT_LANGUAGE']);

                foreach ($browser_languages as $browser_language) {
                    foreach ($languages as $key => $value) {
                        if ($value['status']) {
                            $locale = explode(',', $value['locale']);

                            if (in_array($browser_language, $locale)) {
                                $detect = $key;
                            }
                        }
                    }
                }
            }

        if (isset($session->data['language']) 
            && array_key_exists($session->data['language'], $languages) 
            && $languages[$session->data['language']]['status']) {
                $code = $session->data['language'];
            } elseif (isset($request->cookie['language']) 
                && array_key_exists($request->cookie['language'], $languages) 
                && $languages[$request->cookie['language']]['status']) {
                    $code = $request->cookie['language'];
                } elseif ($detect) {
                    $code = $detect;
                }

        if (!isset($session->data['language']) 
            || $session->data['language'] != $code) {
                $session->data['language'] = $code;
            }

        if (!isset($request->cookie['language']) 
            || $request->cookie['language'] != $code) {	  
                setcookie('language', $code, time() + 60 * 60 * 24 * 30, '/', $request->server['HTTP_HOST']);
            }

        return $languages[$code];

    }
}
